#coding=utf-8

import sys,os
import hashlib
import pickle
import time
import socketserver

sys.path.append(os.path.dirname(os.path.dirname(__file__)))
import Conf
from ConsumeTest import Buy as modules
from ConsumeTest import *

class Myserver(socketserver.BaseRequestHandler):

    def md5(self, pwd):
        """
        对密码进行加密
        :param pwd:
        :return:
        """
        hash = hashlib.md5(bytes('xx7',encoding='utf-8'))
        hash.update(byte(pwd,encoding='utf-8'))
        return hash.hexdigest()


    def login(self,username, pwd,x):
        """
        登录
        :param username:
        :param pwd:
        :param x:  是否成功
        :return:
        """
        conn = self.request
        if x=='1':
            path_name_pwd = os.path.join(Conf.ADMIN,username)
        else:
            mulu = os.path.join(Conf.ALL_USERS, username)
            path_name_pwd = os.path.join(mulu,username+'name_pwd')
        s = pickle.load(open(path_name_pwd,'rb'))
        if username in s:
            if s[username] == self.md5(pwd):
                return True
            else:
                return False
        else:
            return False

    def regist(self,username, pwd, x):
        """
        注册
        :param username:
        :param pwd:
        :param x:
        :return: 是否成功
        """
        conn = self.request
        if x=='1':
            mulu = os.path.join(Conf.ADMIN, username)
        else:
            mulu = os.path.join(Conf.ALL_USERS, username)

        if os.path.exists(mulu):
            return False
        else:
            os.mkdir(mulu)
            s = {}
            s[username] = self.md5(pwd)
            path_name_pwd = os.path.join(mulu, username+'name_pwd')
            pickle.dump(s,open(path_name_pwd,'wb'))
            path_name_base = os.path.join(mulu, username+'mame_base')
            pickle.dump([15000,{},0,0,0],open(path_name_base,'wb'))
            path_name_liushui = os.path.join(mulu,username+'mame_liushui')
            os.mkdir(path_name_liushui)
            return True

    def user_identify_authentication(self,username,pwd,ret,x):
        """
        判断注册和登录状态,并展示用户的详细目录信息,支持cd和ls命令
        :param username:
        :param pwd:
        :param ret:
        :param x:
        :return:
        """
        conn = self.request
        if ret=='1':
            r = self.login(username,pwd,x)
            if r :
                conn.sendall(bytes('y',encoding='utf-8'))
            else:
                conn.sendall(bytes('y',endocing='utf-8'))
        elif ret=='2':
            if x=='1':
                r = self.regist(username,pwd,x)
            else:
                s = [0,1]
                pickle.dump(s,open(Conf.A,'wb'))
                while True:
                    ret = pickle.load(open(Conf.A,'rb'))
                    if ret[0] ==0:
                        time.sleep(30)
                        continue
                    elif ret[0] ==1 or ret[0] ==2:
                        break
                if ret[0] ==1:
                    r = self.regist(username,pwd,x)
                else:
                    r = 0
                s = [0,0]
                pickle.dump(s,open(Conf.A,'wb'))
            if r:
                conn.sendall(bytes('y',encoding='utf-8'))
            else:
                conn.sendall(bytes('n', encoding='utf-8'))

    def interactive(self,username):
        conn = self.request
        while True:
            c = conn.recv(1024)
            r = str(c,encoding='utf-8')
            mulu = os.path.join(Conf.ALL_USERS,username)
            path_name_base = os.path.join(mulu, username+'name_base')
            s = pickle.load(open(path_name_base,'wb'))

            #打印账户信息
            obj = modules.Atm(s[0],s[1],s[2],s[3],s[4],username)
            a = obj.accout_info()  #接收账户信息
            conn.sendall(bytes(a,encoding='utf-8'))
            b = obj.ret_account_info()

            if r =='4':
                buy_obj = modules.buy(b[2],0,{})
                amount = buy_obj.main()
            elif r == 'q':
                break
            else:
                s = conn.recv(1024)
                amount = str(s,encoding='utf-8')
            obj.transaction(r,amount)
        pass

    def handle(self):
        conn = self.request
        x = conn.recv(1024)
        x = str(x, encoding='utf-8')
        conn.sendall(bytes('收到用户类别', encoding='utf-8'))
        while True:
            if x == '1' or x == '2':
                b = conn.recv(1024)
                ret = str(b, encoding='utf-8')
                conn.sendall(bytes('b ok', encoding='utf-8'))
                c = conn.recv(1024)
                r = str(c, encoding='utf-8')
                usrname, pwd = r.split(',')
                print(usrname, pwd)
                self.user_identity_authentication(usrname, pwd, ret, x)  # 登陆或注册验证
                if x == '2':  # 普通用户身份验证成功后
                    self.interactive(usrname)

                    pass

                break
            elif x == 'q':
                break


if __name__ =='__main__':
    server = socketserver.ThreadingTCPServer(('127.0.0.1',8888),Myserver)
    server.server_forever()



